package com.boyou.sytzc.ui.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.TextView
import com.boyou.sytzc.R
import com.boyou.sytzc.data.entity.ServerLocalInfoEntity

class ServerLocalListAdapter(private val ctx: Context, private val dataSource: MutableList<ServerLocalInfoEntity>?) : BaseAdapter() {

	private var checkedIndex: Int = -1

	var checkedItem: ServerLocalInfoEntity? = null
		private set
		get() = dataSource?.getOrNull(checkedIndex)

	override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
		val itemData = dataSource?.get(position)
		var itemView: View? = convertView
		val holder: ViewHolder
		if (itemView == null) {
			itemView = View.inflate(ctx, R.layout.item_for_server_local, null)
			holder = ViewHolder()
			holder.txtItem = itemView?.findViewById<TextView>(R.id.txtServer)
			holder.cbCheck = itemView?.findViewById<CheckBox>(R.id.cbCheck)
			itemView?.tag = holder
		} else {
			holder = itemView.tag as ViewHolder
			itemView = convertView
		}
		holder.cbCheck?.setOnCheckedChangeListener(null)
		holder.cbCheck?.isChecked = checkedIndex == position
		holder.txtItem?.text = itemData?.name
		itemView?.setOnClickListener {
			checkedIndex = if (checkedIndex == position) -1 else position
			notifyDataSetChanged()
		}
		holder.cbCheck?.setOnCheckedChangeListener { _, isChecked ->
			checkedIndex = if (isChecked) position else -1
			notifyDataSetChanged()
		}
		return itemView!!
	}

	override fun getItem(position: Int): Any? = dataSource?.get(position)

	override fun getItemId(position: Int): Long = position.toLong()

	override fun getCount(): Int = dataSource?.size ?: 0

	private inner class ViewHolder {

		var txtItem: TextView? = null

		var cbCheck: CheckBox? = null

	}
}